import { request } from '../../request/index'
import TimeShow from '../../utils/TimeShow'
var { formatTime } = require('../../utils/Time')
//消息协议
var SocketMessage = require('../../utils/SocketMessage')
var timeUtil = require('../../utils/Time')
Page({
  data: {
    num: [],
    isT: false,
    userId: null,
    color: ['#2D4DB6', '#04B67C', '#D1AF07', '#E27914', '#CB4A4D', '#B02690'],
    contentEle: [],
    direction: '-1',
    speed: 400,
    topSex: [],
    leftBt: true,
    rightBt: false,
    toppx: 390
  },
  curentPage: 1,
  userInfo: null,
  qtype: 0,
  timer: null,
  nohave: false,

  // 屏幕滚动
  onPageScroll: function (ev) {
    let _this = this
    if (ev.scrollTop > 200) {
      this.setData({
        isT: true
      })
    } else {
      this.setData({
        isT: false
      })
    }
    //给scrollTop重新赋值
    setTimeout(function () {
      _this.scrollTop = ev.scrollTop
    }, 0)
  },

  // 下拉刷新
  onPullDownRefresh() {
    clearInterval(this.timer)
    this.getQiang(this.data.type, 0)
    this.curentPage = 1
    this.nohave = false
  },
  onReachBottom() {
    this.curentPage += 1
    this.getQiang(this.data.type, this.curentPage)
  },
  onLoad: async function (options) {
    this.userInfo = wx.getStorageSync('userInfo')
    this.getQiang(options.type, 1)
    this.qtype = options.type
    this.setData({
      type: options.type,
      userId: wx.getStorageSync('userId')
    })
  },

  onReady() {
    // this.innit()
  },
  onUnload() {
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
  },

  handend() {
    const timer = setInterval(() => {
      this.animate()
    }, 20)
    this.setData({
      timer,
      speed: 400
    })
  },

  async handChang(e) {
    const { id } = e.currentTarget.dataset
    let dian = wx.getStorageSync('dian')
    if (!dian) dian = []
    // if(dian.includes(id)) return
    let { num } = this.data
    let userid = null
    const dianData = {
      postId: id,
      uId: this.data.userId,
      cTime: formatTime(new Date())
    }
    const { data } = await request({
      url: `/like/${JSON.stringify(dianData)}/${this.qtype}`,
      method: 'post'
    })
    console.log(data)
    if (data.state == 1) {
      num.some((item) => {
        if (item.id === id) {
          item.isClick = true
          item.likeNum += 1
          userid = item.userid
          return true
        }
      })

      dian.push(id)
      wx.setStorageSync('dian', dian)
      const dainData = {
        userId: this.data.userId,
        chatId: userid,
        message: `${this.userInfo.nickName}赞了你`,
        messageType: SocketMessage.GREAT,
        stime: timeUtil.formatTime(new Date())
      }
      wx.sendSocketMessage({
        data: JSON.stringify(dainData)
      })
    }
    if (data.state == 2) {
      num.some((item) => {
        if (item.id === id) {
          item.isClick = false
          item.likeNum -= 1
          return true
        }
      })
      dian.some((item, i) => {
        if (item == id) {
          dian.splice(i, 1)
          return true
        }
      })
      wx.setStorageSync('dian', dian)
    }
    const newNums = this.setNums(num)
    this.setData({
      num,
      newNums
    })
  },

  // 动态详情页
  HandXiangQiang(e) {
    const { id } = e.currentTarget.dataset
    let { num } = this.data
    let don = null
    num.some((item) => {
      if (item.id === id) {
        don = item
        return true
      }
    })
    wx.navigateTo({
      url:
        '/pages/details/details?num=' +
        JSON.stringify(don) +
        '&type=' +
        this.qtype
    })
  },

  handUser(e) {
    const { userid, username } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/personal/personal?userId=${userid}&username=${username}`
    })
  },

  // 墙数据
  async getQiang(type, curentPage) {
    if (this.nohave) return
    const { data } = await request({
      url: `/posts/${type}/${curentPage}`,
      method: 'post'
    })
    console.log(data)
    if (data.state == -2) {
      wx.stopPullDownRefresh()
      wx.showToast({
        title: '刷新太快了哦',
        icon: 'error',
        duration: 2000
      })
      return
    }
    if (data.state == 0) {
      wx.showToast({
        title: '出错了',
        icon: 'error',
        duration: 2000
      })
      return
    }
    let nums = this.data.num
    if (curentPage === 0) nums = []
    let { data: num } = data
    if (num.length <= 0) {
      this.curentPage -= 1
      this.nohave = true
      this.setData({
        rightBt: true
      })
      wx.showToast({
        title: '没有了哦',
        icon: 'error',
        duration: 2000
      })
      return
    }
    let dian = wx.getStorageSync('dian')
    if (!dian) dian = []
    num.forEach((item) => {
      if (dian.includes(item.id)) {
        item['isClick'] = true
      } else {
        item['isClick'] = false
      }
      const paths = item.imgPath
      const as = paths.trim().split('|')
      if (!item['imgs']) item['imgs'] = []
      as.forEach((value, index) => {
        if (index < as.length - 1) item['imgs'].push(value)
      })
      item['ctime'] = TimeShow(item['ctime'])
      const { uheadpic } = item
      let headpic = ''
      const ss = uheadpic.split('xd728')
      ss.forEach((value) => {
        if (headpic === '') {
          headpic = value
        } else {
          headpic += `/${value}`
        }
      })
      item['uheadpic'] = headpic
    })
    // 前六个
    let topSex = []
    if (curentPage === 1) {
      topSex = num.slice(0, 6)
    }
    if (this.data.topSex.length <= 0) {
      let { toppx } = this.data
      if (topSex.length <= 3) {
        toppx = 195
      }
      this.setData({
        topSex,
        toppx
      })
    }
    nums = [...nums, ...num]
    const contentEle = nums.map(() => ({
      x: 0,
      y: 0,
      z: 0,
      style: {}
    }))
    const newNums = this.setNums(nums)
    this.setData(
      {
        num: nums,
        newNums,
        contentEle
      },
      () => {
        wx.stopPullDownRefresh()
        this.innit()
      }
    )
  },
  // 处理奇偶 左右两边数据
  setNums(nums) {
    let newNums = {
      leftNums: [],
      rightNums: []
    }
    if (nums.length > 0) {
      nums.forEach((item, index) => {
        if ((index + 1) % 2 !== 0) {
          newNums.leftNums.push(item)
        } else {
          newNums.rightNums.push(item)
        }
      })
    }
    return newNums
  },

  innit() {
    const RADIUSX = (500 - 50) / 2
    const RADIUSY = (500 - 50) / 2
    let contentEle = []
    for (let i = 0; i < this.data.num.length; i += 1) {
      const k = -1 + (2 * (i + 1) - 1) / this.data.num.length
      const a = Math.acos(k)
      const b = a * Math.sqrt(this.data.num.length * Math.PI)
      const x = RADIUSX * Math.sin(a) * Math.cos(b)
      const y = RADIUSY * Math.sin(a) * Math.sin(b)
      const z = RADIUSX * Math.cos(a)
      const singleEle = {
        x,
        y,
        z,
        style: {}
      }
      contentEle.push(singleEle)
    }
    this.setData(
      {
        contentEle
      },
      () => {
        this.animate()
        this.timer = setInterval(() => {
          this.animate()
        }, 20)
      }
    )
  },
  animate() {
    let contentEle = this.rotateX()
    contentEle = this.rotateY(contentEle)
    this.move(contentEle)
    // window.requestAnimationFrame(this.animate)
  },
  rotateX() {
    const angleX = ['-1', '1'].includes(this.data.direction)
      ? Math.PI / Infinity
      : Math.PI / ((Number(this.data.direction) / 2) * Number(this.data.speed))
    const cos = Math.cos(angleX)
    const sin = Math.sin(angleX)
    const contentEle = this.data.contentEle.map((t) => {
      const y1 = t.y * cos - t.z * sin
      const z1 = t.z * cos + t.y * sin
      return {
        ...t,
        y: y1,
        z: z1
      }
    })
    // this.setData({
    //   contentEle
    // })
    return contentEle
  },
  rotateY(contentEle) {
    const angleY = ['-2', '2'].includes(this.data.direction)
      ? Math.PI / Infinity
      : Math.PI / (Number(this.data.direction) * Number(this.data.speed))
    const cos = Math.cos(angleY)
    const sin = Math.sin(angleY)
    const contentEle1 = contentEle.map((t) => {
      const x1 = t.x * cos - t.z * sin
      const z1 = t.z * cos + t.x * sin
      return {
        ...t,
        x: x1,
        z: z1
      }
    })
    // this.setData({
    //   contentEle
    // })
    return contentEle1
  },
  move(contentEle) {
    const CX = 500 / 2
    const CY = 500 / 2
    const contentEle2 = contentEle.map((singleEle) => {
      const { x, y, z } = singleEle
      const fallLength = 500
      const RADIUS = (500 - 50) / 2
      const scale = fallLength / (fallLength - z)
      const alpha = (z + RADIUS) / (2 * RADIUS)
      const left = `${x + CX - 15}rpx`
      const top = `${y + CY - 15}rpx`
      const transform = `translate(${left}, ${top}) scale(${scale})`
      const style = {
        ...singleEle.style,
        opacity: alpha + 0.5,
        zIndex: parseInt(scale * 100, 10),
        transform
      }
      return {
        x,
        y,
        z,
        style
      }
    })
    this.setData({
      contentEle: contentEle2
    })
  },

  // 手动滑动
  touchStart(e) {
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      speed: 80
    })
  },
  touchMove(e) {
    const startX = this.data.startX
    const startY = this.data.startY
    // 滑动后坐标
    let moveX = e.changedTouches[0].clientX
    let moveY = e.changedTouches[0].clientY
    // 滑动角度
    let angle = this.angle({ X: startX, Y: startY }, { X: moveX, Y: moveY })
    if (Math.abs(angle) > 30) return true
    if (moveX > startX) {
      this.setData(
        {
          direction: '-1',
          startX: moveX,
          startY: moveY
        },
        () => {
          this.animate()
        }
      )
    } else {
      this.setData(
        {
          direction: '1',
          startX: moveX,
          startY: moveY
        },
        () => {
          this.animate()
        }
      )
    }
  },
  // 计算滑动角度
  // @param {Object} start 起点坐标
  // @param {Object} end 终点坐标
  angle(start, end) {
    var _X = end.X - start.X
    var _Y = end.Y - start.Y
    return (360 * Math.atan(_Y / _X)) / (2 * Math.PI)
  },

  navCreate() {
    // wx.setStorageSync('qtype', this.qtype)
    getApp().globalData.qtype = this.qtype
    wx.switchTab({
      url: '/pages/create/create'
    })
  },

  async changeCurent(e) {
    wx.vibrateShort({
      type: 'medium'
    })
    const { setpage } = e.currentTarget.dataset
    if (setpage === -1 && this.data.rightBt) {
      this.setData({
        rightBt: false
      })
    }
    this.curentPage = this.curentPage + setpage
    if (this.curentPage > 1) {
      this.setData({
        leftBt: false
      })
    } else {
      this.setData({
        leftBt: true
      })
    }
    const { data } = await request({
      url: `/posts/${this.data.type}/${this.curentPage}`,
      method: 'post'
    })
    console.log(data)
    if (data.state == -2) {
      wx.showToast({
        title: '点太快了哦',
        icon: 'error',
        duration: 2000
      })
      return
    }
    if (data.state == 0) {
      wx.showToast({
        title: '出错了',
        icon: 'error',
        duration: 2000
      })
      return
    }
    const { data: num } = data
    num.forEach((item) => {
      const paths = item.imgPath
      const as = paths.trim().split('|')
      if (!item['imgs']) item['imgs'] = []
      as.forEach((value, index) => {
        if (index < as.length - 1) item['imgs'].push(value)
      })
      item['ctime'] = TimeShow(item['ctime'])
      const { uheadpic } = item
      let headpic = ''
      const ss = uheadpic.split('xd728')
      ss.forEach((value) => {
        if (headpic === '') {
          headpic = value
        } else {
          headpic += `/${value}`
        }
      })
      item['uheadpic'] = headpic
    })
    if (num.length <= 0) {
      this.curentPage -= 1
      this.setData({
        rightBt: true
      })
      wx.showToast({
        title: '没有了哦',
        icon: 'error',
        duration: 2000
      })
      return
    }
    this.setData({
      num
    })
  }
})
